<?php
/**
 * 下载专区
 */
class DownloadApp extends CommonApp {

    //通用文件下载专区
    public function downloadAct(){
        $result = self::getList('download');
        self::assign_seo('download');
        //把文件路径中的/用-替换掉，以便文件下载时方便传递下载参数
//     	foreach($result['data'] as &$value)
//           $value['params']['files'] = str_replace('/', '-', $value['params']['files']);
        $this->assign('menu',self::menu('download'));
        $this->assign('result',$result);
        $this->assign('download',true);
        $this->display('Common/index');
    }
    //政策文件下载专区
    public function policyAct(){
        $result = self::getList('policy');
        self::assign_seo('policy');
        //把文件路径中的/用-替换掉，以便文件下载时方便传递下载参数
//      foreach($result['data'] as &$value)
//           $value['params']['files'] = str_replace('/', '-', $value['params']['files']);
        $this->assign('menu',self::menu('policy'));
        $this->assign('result',$result);
        $this->assign('download',true);
        $this->display('Common/index');
    }
    //项目文件下载专区
    public function articleAct(){
        $result = self::getList('article');
        self::assign_seo('article');
        //把文件路径中的/用-替换掉，以便文件下载时方便传递下载参数
//      foreach($result['data'] as &$value)
//           $value['params']['files'] = str_replace('/', '-', $value['params']['files']);
        $this->assign('menu',self::menu('article'));
        $this->assign('result',$result);
        $this->assign('download',true);
        $this->display('Common/index');
    }
    //素拓文件下载专区
    public function sutuoAct(){
        $result = self::getList('sutuo');
        self::assign_seo('sutuo');
        //把文件路径中的/用-替换掉，以便文件下载时方便传递下载参数
//      foreach($result['data'] as &$value)
//           $value['params']['files'] = str_replace('/', '-', $value['params']['files']);
        $this->assign('menu',self::menu('sutuo'));
        $this->assign('result',$result);
        $this->assign('download',true);
        $this->display('Common/index');
    }
    //导师资料下载专区
    public function tutorAct(){
        $result = self::getList('tutor');
        self::assign_seo('tutor');
        //把文件路径中的/用-替换掉，以便文件下载时方便传递下载参数
//      foreach($result['data'] as &$value)
//           $value['params']['files'] = str_replace('/', '-', $value['params']['files']);
        $this->assign('menu',self::menu('tutor'));
        $this->assign('result',$result);
        $this->assign('download',true);
        $this->display('Common/index');
    }
    //成果档案下载专区
    public function recordAct(){
        $result = self::getList('record');
        self::assign_seo('record');
        //把文件路径中的/用-替换掉，以便文件下载时方便传递下载参数
//      foreach($result['data'] as &$value)
//           $value['params']['files'] = str_replace('/', '-', $value['params']['files']);
        $this->assign('menu',self::menu('record'));
        $this->assign('result',$result);
        $this->assign('download',true);
        $this->display('Common/index');
    }


    /**
     * 官网附件下载
     **/
    public function fileDownloadAct(){
        //下载文件的链接（GET提交过来的file_path字符串要把-替换为/）
        $id = I('post.id');
        if(!My::is_id($id))
            $this->ajaxReturn(404,'id有误!');
        //尝试获取附件原文件名
        $file_name = DB('datas')->where("`id`='{$id}'")->cache()->field('title,params')->find();
        $file_name['params'] = My::decodeJson($file_name['params']);
        //下载文件绝对路径
        $file_path = PUB_DIR.$file_name['params']['files'];    
        if(!file_exists($file_path))
            $this->ajaxReturn(404,'文件不存在!');
        $result = $this->fileDownload2($file_name['title'],$file_name['params']['files']);
        if($result) $this->ajaxReturn(200,$result);
        else $this->ajaxReturn(200,'文件打包出错！');
        // redirect();
    }

//     /**
//      * 单个项目打包下载
//      **/
    function fileDownload2($title='',$file_path=''){
        $Files = new ZipArchive();// 实例化上传类
        $file_name = "share/images/temp/".strtotime(date("Y-m-d H:i:s")).".zip";//临时打包的项目文件zip
        $Files->open($file_name,\ZipArchive::CREATE);
        // if(!file_exists($file_path))
        //     continue;
        $name = $title.'.'.pathinfo($file_path, PATHINFO_EXTENSION);//文件名
        $Files->addFromString(iconv('utf-8', 'gbk',$name),file_get_contents($file_path));//中文使用这个
        if($Files->close()){
            //删除1天前的文件
            $dir = realpath('./share/images/temp');
            $this->z_del_file_by_ctime($dir, 60);
            //替换打包好的文件路劲
            return $file_name;
        }else return false;
    }

    /**
     * 批量附件打包
     **/
    public function filesDownloadAct(){
        if($_POST){
            $Files = new ZipArchive();// 实例化上传类
            $file_name = "share/images/temp/".strtotime(date("Y-m-d H:i:s")).".zip";//临时打包的项目文件zip
            $Files->open($file_name,\ZipArchive::CREATE);
            $_POST['files'] = explode(",",$_POST['files']);
            $_POST['title'] = explode(",",$_POST['title']);
            foreach ($_POST['files'] as $key => $value){
//                $link = str_replace('-', '/', $value);
                if(!file_exists($value))
                    continue;
                $name = $_POST['title'][$key].'.'.pathinfo($value, PATHINFO_EXTENSION);//文件名
//                $Files->addFile($link,$_POST['title'][$key]);
                $Files->addFromString(iconv('utf-8', 'gbk',$name),file_get_contents($value));//中文使用这个
            }
            if($Files->close()){
                //删除1天前的文件
                $dir = realpath('./share/images/temp');
                $this->z_del_file_by_ctime($dir, 60);
                //替换打包好的文件路劲
//                $file_path2 = str_replace('/', '-', $file_name);
                $this->ajaxReturn(200,$file_name);
            }else $this->ajaxReturn(300,'文件打包出错');

        }
    }

//    /**
//     * 批量附件下载
//     **/
//    public function filesDownload2Act(){
//        $link = str_replace('-', '/', I('get.file_path'));
//        //下载文件绝对路径
//        $file_path = PUB_DIR.$link;
//        if(!file_exists($file_path))
//            $this->ajaxReturn(404,'文件不存在!');
//
//        //附件下载
//        echo File::download($file_path,'项目汇总.zip');
//    }

    /*
     * 删除文件夹下$n分钟前创建的文件
     * @param $dir 要处理的目录，物理路径，结尾不加\
     * @param $n 过期时间，单位为分钟
     * @return void
     */
    function z_del_file_by_ctime($dir,$n){
        if(is_dir($dir)){
            if($dh=opendir($dir)){
                while (false !== ($file = readdir($dh))){
                    if($file!="." && $file!=".."){
                        $fullpath=$dir."/".$file;
                        if(!is_dir($fullpath)){
                            $filedate=filemtime($fullpath);
                            $minutes=round((time()-$filedate)/60);
                            if($minutes>$n)
                                unlink($fullpath); //删除文件
                        }
                    }
                }
            }
            closedir($dh);
        }
    }
}